<template>
  <div class="employees-container">
    <CardHeader>
      <!-- <template> -->
      <el-button v-showbutton="'POINT-USER-IMPROT'" type="success" size="small" @click="$router.push('/import')">导入</el-button>
      <el-button v-if="showButton('POINT-USER-EXPORT')" type="warning" size="small" @click="handleDownload">导出</el-button>
      <el-button type="primary" size="small" @click="showDialog = true">+ 新增员工</el-button>
      <!-- </template> -->
      <template #left>总记录条数：{{ total }}条</template>
    </CardHeader>
    <el-card>
      <el-table :data="list">
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="姓名" prop="username" width="150" align="center" />
        <el-table-column label="员工图片" align="center">
          <template v-slot="{ row }">
            <img
              v-imagerror="require('@/assets/common/bigUserHeader.png')"
              width="80px"
              height="80px"
              :src="row.staffPhoto"
              alt=""
              @click="showCode(row.staffPhoto)"
            >
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" align="center" />
        <el-table-column label="聘用形式" align="center">
          <template v-slot="{ row }">
            <span>{{ +row.formOfEmployment === 1 ? '正式' : '非正式' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" align="center" />
        <el-table-column label="入职时间" align="center">
          <template v-slot="{ row }">
            <span>{{ row.timeOfEntry | time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="账户状态" prop="enableState" align="center">
          <template v-slot="{ row }">
            {{ row.enableState === 1 ? '可用': '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template v-slot="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/details/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end">
        <el-pagination
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          :current-page="page"
          background
          @current-change="currentChange"
        />
      </el-row>
      <!-- 二维码弹窗 -->
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </el-card>
    <AddEmployees :show-dialog.sync="showDialog" @getEmployeesList="getEmployeesList" />
    <AssignRoles :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeesList, delEmployees } from '@/api/employees'
import EmployeesEnum from '@/api/constant/employees'
import AddEmployees from './AddEmployees.vue'
import AssignRoles from './assignRoles.vue'
import moment from 'moment'
import Qrcode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployees,
    AssignRoles
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 5,
      total: 0,
      hireType: EmployeesEnum.hireType,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 控制按钮级别的显示和隐藏，考虑到复用性，可以挂载到vue原型或者封装成自定义指令
    showButton(code) {
      // console.log(code)
      const roles = this.$store.state.user.userInfo.roles
      // console.log(pionts)
      if (!roles) {
        return false
      } else {
        return roles.points.some(item => item === code)
      }
    },
    async getEmployeesList() {
      const data = await getEmployeesList(this.page, this.size)
      // console.log(data)
      this.list = data.rows
      this.total = data.total
    },
    async currentChange(value) {
      // console.log(value)
      this.page = value
      const { rows, total } = await getEmployeesList(this.page, this.size)
      // console.log(rows)
      this.total = total
      this.list = rows
      // this.getEmployeesList()
    },
    async delFn(id) {
      try {
        await this.$confirm('你确定要删除该员工吗？', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      await delEmployees(id)
      this.$message.success('删除成功')
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      this.getEmployeesList()
    },
    handleDownload() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      this.downloadLoading = true
      import('@/utils/Export2Excel').then(async excel => {
        const tHeader = Object.keys(headers)
        const { rows } = await getEmployeesList(1, this.total)
        // console.log(rows)
        const tData = []
        rows.forEach(item => {
          const arr = []
          Object.values(headers).forEach(k => {
            if (k === 'correctionTime' || k === 'timeOfEntry') {
              const time = moment(item[k]).format('YYYY-MM-DD')
              arr.push(time)
            } else if (k === 'formOfEmployment') {
              +item[k] === 1 ? arr.push('正式') : arr.push('非正式')
            } else {
              arr.push(item[k])
            }
          })
          tData.push(arr)
        })
        // console.log(tHeader, tData)
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data: tData,
          // 文件名
          filename: 'test',
          // 自适应宽度
          autoWidth: true,
          // 后缀名
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    async showCode(photo) {
      this.showCodeDialog = true
      await this.$nextTick()
      Qrcode.toCanvas(this.$refs.myCanvas, photo)
    },
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.employees {
  &-container {
    margin: 30px;
  }
}
</style>
